import React,{useEffect} from 'react';
import { Modal, Form, InputNumber } from 'antd';
import FirstOrgListComponent from './FirstOrgListComponent';
import { FormInstance } from 'antd/lib/form';
import { OrgOrderListItem } from '../data.d';

interface AddOrgOrderFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  onSubmit: (values: OrgOrderListItem) => void;
  values: OrgOrderListItem;
}

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const formRef = React.createRef<FormInstance>();

const AddOrgOrderForm: React.FC<AddOrgOrderFormProps> = (props) => {
  const { modalVisible, onSubmit, onCancel, values } = props;
  const [form] = Form.useForm();

  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      onSubmit(values as OrgOrderListItem);
    }
  };

  const handleUpdate = () => {
    if (!form) return;
    form.submit();
  };

  const modalFooter = { okText: '保存', onOk: handleUpdate, onCancel };

  useEffect(() => {
    if(modalVisible){
      if(!values.id){//新建
        form.resetFields();
      }
    }
  },[modalVisible]);

  const renderContent = () => {
    return (
      <>
        <Form.Item name="id" style={{ display: 'none' }}></Form.Item>
        <Form.Item name="topOrgId" label="所属机构" rules={[{ required: true }]}>
            <FirstOrgListComponent 
              disabled={values?.id?true:false}
              init={true}
              defaultvalue={values?values.topOrgId:null} 
              selectChange={(value) => {
                form.setFieldsValue({topOrgId:value});
              }}>
            </FirstOrgListComponent>
        </Form.Item>
        <Form.Item 
          name="totalNum" 
          label="最大设备数" 
          rules={[{ required: true }]}
          initialValue={1}
          >
            <InputNumber min={1} defaultValue={values.id?values.totalNum:1} onChange={(value)=>{form.setFieldsValue({totalNum:value});}} /> 台
        </Form.Item>
      </>
    );
  };
  return (
    <Modal 
      destroyOnClose 
      title={(values && values.id)?"编辑服务":"添加服务"} 
      visible={modalVisible} 
      {...modalFooter} 
      centered
      >
      <Form 
        {...layout} 
        ref={formRef} 
        form={form}
        initialValues={values}
        onFinish={handleFinish}>
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default AddOrgOrderForm;
